package cn.com.hhrcw.block.web;

import cn.com.hhrcw.block.entity.Block;
import cn.com.hhrcw.block.entity.BlockData;
import cn.com.hhrcw.block.mapstruct.BlockDataConvert;
import cn.com.hhrcw.block.params.BlockDataParams;
import cn.com.hhrcw.block.service.IBlockDataService;
import cn.com.hhrcw.block.service.IBlockService;
import cn.com.hhrcw.block.vo.BlockDataVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.function.Function;

/**
 * 区块
 *
 * @author lixingxing
 * @since 2020-09-16
 */
@RestController
@Slf4j
@RequestMapping("/admin/blockData")
@Validated
public class BlockDataController extends JeecgController<Block, IBlockService> {

    @Autowired
    private BlockDataConvert blockDataConvert;

    @Autowired
    private IBlockDataService blockDataService;

    /**
     * 区块数据列表
     *
     * @param params
     * @param request
     * @return
     */
    @GetMapping("/list")
    public Result<Page> list(BlockDataParams params, HttpServletRequest request) {

        QueryWrapper<BlockData> queryWrapper = QueryGenerator.initQueryWrapper(blockDataConvert.toEntity(params), request.getParameterMap());
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByAsc("sequence", "create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        IPage<BlockData> page = blockDataService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<BlockData, BlockDataVO> fun = blockData -> blockDataConvert.toVO(blockData);

        return Result.ok((Page) page.convert(fun));
    }

}
